<template>
	<div class="common-layout">
		<el-container>
			<!-- 左侧 -->
			<el-aside width="30%">
				<el-card body-style="height: calc(100vh - 170px )">
					<el-form :inline="true" :model="state.queryForm" @keyup.enter="getDataList()">
						<el-form-item size="small" style="width: 170px">
							<el-select v-model="state.queryForm.id" placeholder="选择数据库">
								<el-option v-for="item in state.databaseList" :key="item.value" :label="item.label" :value="item.value" />
							</el-select>
						</el-form-item>
						<el-form-item size="small" style="width: 170px">
							<el-input v-model="state.queryForm.tableName" placeholder="表名" clearable></el-input>
						</el-form-item>
						<el-form-item size="small" style="width: 170px">
							<el-input v-model="state.queryForm.remarks" placeholder="注释" clearable></el-input>
						</el-form-item>
						<!-- <el-form-item size="small">
							<fast-project-select v-model="state.queryForm.projectId" placeholder="所属项目" clearable></fast-project-select>
						</el-form-item> -->
						<el-form-item size="small">
							<el-button type="primary" @click="search()">查询</el-button>
						</el-form-item>
					</el-form>
					<!-- <el-tag style="margin-bottom:10px"><p>tips：此处显示的是通过数据接入同步的表，手动新增的不在范围内</p></el-tag> -->
					<el-table
						v-loading="state.dataListLoading"
						:data="state.dataList"
						border
						style="width: 100%"
						max-height="calc(100vh - 400px )"
						highlight-current-row
						@current-change="handleCurrentChange"
					>
						<!-- <fast-table-project-column prop="projectId" label="所属项目" header-align="center" align="center"></fast-table-project-column> -->
						<fast-table-project-column prop="name" label="数据源名" header-align="center" align="center"></fast-table-project-column>
						<el-table-column prop="tableName" label="表名" header-align="center" align="center"></el-table-column>
						<el-table-column prop="remarks" label="注释" header-align="center" align="center"></el-table-column>
					</el-table>
					<el-pagination
						class="pagination"
						:current-page="state.page"
						:page-sizes="state.pageSizes"
						:page-size="state.limit"
						:total="state.total"
						:pager-count="3"
						layout="total, sizes, prev, pager, next"
						@size-change="sizeChangeHandle"
						@current-change="currentChangeHandle"
					>
						<!-- layout="total, sizes, prev, pager, next, jumper" -->
					</el-pagination>
					<!-- <template v-else>
						<el-empty v-loading="state.dataListLoading" description="暂无数据,请选择数据库"></el-empty>
					</template> -->
				</el-card>
			</el-aside>
			<!-- 右侧主区域 -->
			<el-container>
				<el-header>
					<el-card body-style="height: calc(100vh - 170px )">
						<el-tabs v-model="activeName" class="demo-tabs" @tab-change="handleClick" :before-leave="tabBeforeLeave">
							<el-tab-pane label="表信息" name="tableInfo">
								<el-tag size="large" effect="dark" round style="margin-bottom: 15px"> 表属性 </el-tag>
								<el-descriptions :column="1" direction="horizontal" style="blockMargin">
									<el-descriptions-item label="表名">{{ state.currentRow.tableName }}</el-descriptions-item>
									<el-descriptions-item label="注释">{{ state.currentRow.remarks }}</el-descriptions-item>
									<!-- <el-descriptions-item label="数据接入任务"
										><el-button type="primary" link @click="getAccessInfoHandler()">查看</el-button></el-descriptions-item
									> -->
									<el-descriptions-item label="最近同步时间">{{ state.recentlySyncTime ? state.recentlySyncTime : '暂无' }}</el-descriptions-item>
								</el-descriptions>
								<br />
								<el-tag size="large" effect="dark" round style="margin-bottom: 15px"> 字段信息 </el-tag>
								<el-table :data="state.tableColumns" height="400" style="width: 100%">
									<el-table-column prop="fieldName" label="名称" header-align="center" align="center" />
									<el-table-column prop="remarks" label="注释" header-align="center" align="center" />
									<el-table-column prop="fieldTypeName" label="类型" header-align="center" align="center" />
									<el-table-column prop="displaySize" label="长度" header-align="center" align="center" />
									<el-table-column prop="scaleSize" label="小数位数" header-align="center" align="center" />
									<el-table-column prop="defaultValue" label="默认值" header-align="center" align="center" />
									<el-table-column prop="pk" label="是否主键" header-align="center" align="center" />
									<el-table-column prop="autoIncrement" label="是否递增" header-align="center" align="center" />
									<el-table-column prop="nullable" label="是否可为空" header-align="center" align="center" />
								</el-table>
							</el-tab-pane>
							<el-tab-pane label="数据预览" name="tableData">
								<div v-loading="loadings">
									<p>若超过50条，只显示前50条数据！</p>
									<el-table :data="state.tableData" style="margin-top: 20px; width: 90%" height="600">
										<el-table-column
											:show-overflow-tooltip="true"
											width="100px"
											:prop="index"
											:label="item"
											v-for="(item, index) in state.tableDataHeader"
											:key="index"
										>
										</el-table-column>
									</el-table>
								</div>
							</el-tab-pane>
							<!-- <el-tab-pane label="接入日志" name="tableLog">
								弹窗 同步结果
								<ods-task-detail ref="odsTaskDetailRef"></ods-task-detail>
							</el-tab-pane> -->
							<el-tab-pane label="sql 控制台" name="sqlConsole">
								<div style="padding-top: 5px">
									<el-tooltip class="box-item" effect="dark" content="美化sql" placement="top-end">
										<el-button text @click="formatSql()"><img src="@/assets/format.png" /></el-button>
									</el-tooltip>
									<el-tooltip class="box-item" effect="dark" content="执行" placement="top-end">
										<el-button :loading="executeSqlButton" @click="executeSql()" text><img src="@/assets/run.png" /></el-button>
									</el-tooltip>
								</div>
								<div style="height: calc(100vh - 650px); padding-top: 5px">
									<SqlStudio ref="sqlStudioRef" id="dataTableSqlConsoleId" heightAll></SqlStudio>
								</div>
								<el-tabs class="data-table-tabs">
									<el-tab-pane>
										<template #label>
											<span>
												<el-icon><DataLine /></el-icon>&nbsp;
												<span>执行结果</span>
											</span>
										</template>
										<div style="margin-top: 8px">
											<el-tag>tips：若记录超过100条，只显示前100条记录</el-tag>
										</div>
										<div v-loading="sqlResultLoading" style="height: 320px">
											<console-result ref="consoleResultRef"></console-result>
										</div>
									</el-tab-pane>
								</el-tabs>
							</el-tab-pane>
						</el-tabs>
					</el-card>
				</el-header>
			</el-container>
		</el-container>
	</div>

	<!-- 数据接入 详情 -->
	<info ref="infoRef"></info>
</template>

<script setup lang="ts" name="Data-integrateOdsIndex">
import { useCrud } from '@/hooks'
import { ElMessage, ElMessageBox } from 'element-plus'
import info from '../access/info.vue'
import { IHooksOptions } from '@/hooks/interface'
import { getColumnInfoApi, getTableDataApi, recentApi } from '@/api/data-integrate/ods'
import { useAccessApi } from '@/api/data-integrate/access'
import OdsTaskDetail from './ods-task-detail.vue'
import { odsQuery } from '@/api/auth-hm'
import timeFormater from 'time-formater'

import SideLayout from '@/components/side-layout/index.vue'
import { reactive, ref, onMounted, watch } from 'vue'
import { getMiddleDbColumnsApi } from '@/api/data-governance/masterColumn'
import {
	listMiddleDbTreeApi,
	getTableInfoApi,
	saveTableInfoApi,
	deleteTableInfoApi,
	listMiddleDbColumnsApi,
	getMiddleDbSqlGenerationApi
} from '@/api/data-integrate/database'
import store from '@/store'
import { getDictLabel, getNameByUserId } from '@/utils/tool'
import SqlStudio from './sql-studio.vue'
import ReadOnlyStudio from '../production/readonly-studio.vue'
import ConsoleResult from '../production/console-result.vue'
import { justExecuteSqlApiTwo, clearConsoleLogApiTwo } from '@/api/data-development/task'
const treeRef = ref()
const treeList = ref([])
const filterNodeText = ref('')
const detailLoading = ref(false)
const pickColunmsLoading = ref(false)
const isDetail = ref(false)
const tabActiveName = ref('tableInfo')
const sqlStudioRef = ref()
const consoleResultRef = ref()
const sqlResultLoading = ref(false)
const executeSqlButton = ref(false)
const dbDialogVisible = ref(false)
const tableDialogVisble = ref(false)
const dbInfo = ref({})
const tableColumns = ref([])
const SQLDDLRef = ref()
const SQLSELECTRef = ref()
const loadings = ref(true)

const state: IHooksOptions = reactive({
	dataListUrl: '/data-integrate/ods/page',
	queryForm: {
		id: '',
		tableName: '',
		remarks: '',
		projectId: ''
	},
	currentRow: {},
	tableColumns: [],
	tableData: [],
	tableDataHeader: {},
	databaseList: [],
	dataListLoading: true,
	recentlySyncTime: ''
})

const activeName = ref('')
const tabBeforeLeave = () => {
	if (!state.currentRow.tableName) {
		ElMessage({
			message: '请在左侧选择要查看的表',
			type: 'warning'
		})
		return false
	}
}

const odsTaskDetailRef = ref()
/* tab切换 */
const handleClick = (name: TabPaneName, row: any) => {
	if (name == 'tableData') {
		loadings.value = true
		//查询选中的表数据
		getTableDataApi(state.currentRow.tableName + '/' + state.currentRow.id).then(res => {
			loadings.value = false
			state.tableDataHeader = res.data.columns
			state.tableData = res.data.rows
		})
	} else if (name == 'tableLog') {
		odsTaskDetailRef.value.init(state.currentRow.projectId, state.currentRow.tableName)
	} else {
		tableFun(row)
	}
}
/* 表切换 */
const handleCurrentChange = val => {
	if (!val) {
		return
	}
	state.currentRow = val
	if (activeName.value) {
		handleClick(activeName.value, val)
	} else {
		activeName.value = 'tableInfo'
		handleClick('tableInfo', val)
	}
}
const tableFun = row => {
	state.tableColumns = []
	state.tableData = []
	state.tableDataHeader = {}
	state.recentlySyncTime = ''
	getColumnInfoApi(row.tableName + '/' + row.id).then(res => {
		state.tableColumns = res.data
	})
	recentApi(row.tableName + '/' + row.id).then(res => {
		let times = ''
		if (res.data) {
			times = timeFormater(res.data).format('YYYY-MM-DD hh:mm:ss')
			state.recentlySyncTime = times
		} else {
			state.recentlySyncTime = ''
		}
	})
}
const infoRef = ref()
/* 查看表的数据接入任务 */
const getAccessInfoHandler = () => {
	if (!state.currentRow.dataAccessId) {
		ElMessage({
			message: '没有查询到该表对应的数据接入任务',
			type: 'warning'
		})
		return
	}
	useAccessApi(state.currentRow.dataAccessId).then(res => {
		if (!res.data) {
			ElMessage({
				message: '该任务已被删除，若要恢复，请联系管理员处理',
				type: 'warning'
			})
			return
		}
		infoRef.value.init(state.currentRow.dataAccessId)
	})
}
onMounted(() => {
	odsQueryFun()
})
const odsQueryFun = () => {
	state.databaseList = []
	odsQuery('1').then((res: any) => {
		if (res.code == 0) {
			let dataList = res.data && res.data.length > 0 ? res.data : []
			let dataObj = []
			for (let i = 0; i < dataList.length; i++) {
				let obj = {
					value: '',
					label: ''
				}
				obj.value = dataList[i].id
				obj.label = dataList[i].name
				dataObj.push(obj)
			}
			state.databaseList = dataObj
			state.queryForm.id = dataObj[0].value
			state.dataListLoading = true
			getDataList()
		} else {
			ElMessage.error(res.msg)
		}
	})
}
// sql控制台

const executeSql = () => {
	sqlResultLoading.value = true
	executeSqlButton.value = true
	const sqlDataForm = {}
	sqlDataForm.sqlDbType = 2
	sqlDataForm.databaseId = state.currentRow.id
	sqlDataForm.maxRowNum = 100
	sqlDataForm.statement = sqlStudioRef.value.getEditorValue()
	if (!sqlDataForm.statement) {
		ElMessage.warning('请输入sql！')
		sqlResultLoading.value = false
		executeSqlButton.value = false
		return
	}
	justExecuteSqlApiTwo(sqlDataForm).then(res => {
		const data = res.data
		if (!data.success) {
			ElMessage.error('执行失败，请查看日志信息排查原因！')
			consoleResultRef.value.init(data.result, 1)
		} else {
			ElMessage.success('执行成功')
			consoleResultRef.value.init(data.result, 1)
		}
		sqlResultLoading.value = false
		executeSqlButton.value = false
		//清空后台产生的日志
		clearConsoleLogApiTwo()
	})
}

//，美化sql
const formatSql = () => {
	sqlStudioRef.value!.handleFormat()
}

/**
 * 右键相关参数
 */
const ckRightOptionData = reactive({
	optionCardShow: false,
	optionCardX: 0,
	optionCardY: 0,
	optionData: {},
	node: '',
	tree: ''
})

/**
 * 右键节点
 */
const ckRightOption = (e, data, n, t) => {
	ckRightOptionData.optionCardShow = false
	ckRightOptionData.optionCardX = e.x // 让右键菜单出现在鼠标右键的位置
	ckRightOptionData.optionCardY = e.y
	ckRightOptionData.optionData = data
	ckRightOptionData.node = n // 将当前节点保存
	ckRightOptionData.tree = t
	//如果不是分层
	if (data.type != '2') {
		ckRightOptionData.optionCardShow = true // 展示右键菜单
	}
}

/**
 * 点击右键菜单以外的地方
 */
const OptionCardClose = event => {
	var currentCli = document.getElementById('option-button-group')
	if (currentCli) {
		ckRightOptionData.optionCardShow = false
	}
}

const search = e => {
	activeName.value = ''
	sqlStudioRef.value.setEditorValue('')
	consoleResultRef.value.clear()
	setTimeout(() => {
		state.currentRow.tableName = ''
		getDataList()
	}, 100)
}
const { getDataList, selectionChangeHandle, sizeChangeHandle, currentChangeHandle, deleteBatchHandle } = useCrud(state)
</script>

<style>
.demo-tabs > .el-tabs__content {
	padding: 18px;
	color: #6b778c;
}
</style>
<style lang="scss" scoped>
:deep(.pagination) {
	width: 100%;
	display: block;
	text-align: right;
	.el-pagination__sizes {
		margin-left: 10px;
		width: 98px;
		display: inline-block;
		.el-input--suffix {
			width: 100%;
		}
	}
	.btn-prev {
		display: inline-block;
		margin-left: 5px;
	}
	.el-pager {
		display: inline-block;
		li {
			display: inline-block;
		}
	}
	.btn-next {
		display: inline-block;
	}
}
.tableList .fieldName {
	display: inline-block;
}
// 右键菜单按钮
.option-card-button {
	width: 100%;
	margin-left: 0 !important;
	padding: 20px 20px;
	font-size: 14px;
	border-radius: 0;
}
/* 树节点相关属性 */
.DataTableTreeDiv .el-tree-node__content {
	height: 35px;
}
.dataTable-tree-node {
	font-size: 16px;
	-webkit-user-select: none;
	-khtml-user-select: none;
	-moz-user-select: none;
	-ms-user-select: none;
	user-select: none;
}

.data-table-right {
	padding: 0 !important;

	.dsr-part {
		overflow: hidden;
	}

	.action_part {
		background-color: #fff;
		padding: 12px;
		border-bottom: 1px solid #ebeef5;
		box-sizing: border-box;
	}

	.info-part {
		background-color: #eef3fd;
		width: calc(100% - 20px);
		margin: 12px auto 0;
		border: 1px solid #ebeef5;
		padding: 12px;
		box-sizing: border-box;
		border-radius: 8px;

		h6 {
			padding: 12px 0;
			padding-left: 20px;
			position: relative;
			font-size: 16px;
			font-family: Alibaba-PuHuiTi-M, Alibaba-PuHuiTi;
			font-weight: normal;
			color: #020e19;

			&::after {
				content: '';
				height: 12px;
				width: 4px;
				position: absolute;
				left: 6px;
				top: 50%;
				transform: translateY(-50%);
				// background-color: $--color-primary;
				background: linear-gradient(180deg, #10b0f9 0%, rgba(25, 104, 249, 0.3) 100%);
			}
		}
	}
}

.sheet-field {
	.error_tips .el-input__inner {
		border-color: #f56c6c;
	}
	.addName {
		color: #667afa;
	}
}
.sheet_field_column {
	.no_check {
		.el-table-column--selection .cell {
			display: none;
		}
	}
	.select_box {
		border: 1px solid #ebeef5;
		height: 100px;
		overflow-x: hidden;
		overflow-y: auto;
		padding: 10px;
		border-radius: 4px;
		margin-bottom: 16px;
		.el-tag {
			margin-bottom: 10px;
			margin-right: 10px;
		}
	}
}

.data-table-tabs > .el-tabs__content {
	padding: 0;
}
.data-table-tabs > .el-tabs__header {
	margin: 0;
}
</style>
